<?php

    /**
    * Mikron.ORM
    * 19-05-2009
    * Author: sciner@yandex.ru
    */

    session_start();
    ini_set('display_errors', E_ALL);
    error_reporting(E_ALL | E_STRICT);
    ini_set('default_charset', 'utf-8');
    @ini_set('zend.ze1_compatibility_mode', '0');
    ini_set('pcre.backtrack_limit', '100000000000');
    setlocale(LC_ALL, 'ru_RU.UTF8','ru_RU.UTF-8'); 
    header('Content-Type: text/html; charset=UTF-8');
    iconv_set_encoding('internal_encoding', 'UTF-8');
    iconv_set_encoding('output_encoding', 'UTF-8');
    date_default_timezone_set('Europe/Moscow');

    // set to the user defined error handler
    $old_error_handler = set_error_handler('mikronErrorHandler', E_WARNING | E_NOTICE); //E_WARNING | E_NOTICE | E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING
    /**
    * Error handler function
    */
    function mikronErrorHandler($errno, $errstr, $errfile, $errline)
    {
        /*if(ob_get_level() > 0)
        {
            ob_clean();
        }*/
        echo sprintf('<strong>Error:</strong> [%s] <code>%s</code> in %s on line %s', $errno, $errstr, str_replace($_SERVER['DOCUMENT_ROOT'], '...', str_replace('\\', '/', $errfile)), $errline);
        //exit(1);
        //throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
        // Don't execute PHP internal error handler
        return true;
    }

    define('VARQUOTESTART', "{{");
    define('VARQUOTEEND', "}}");
    define('CMS_DIRECTORY', correctPath(dirname(__FILE__)).'/admin');
    define('RUN_TIME_KEY', md5(time().rand(0, 999999999)));
    define('MIKRON_DIRECTORY', correctPath(dirname(__FILE__)));
    define('MIKRON_LIBDIR', correctPath(dirname(__FILE__).'/lib'));
    define('MIKRON_DIRECTORY_WWW', correctPath(WWWDirName(__FILE__)));
    define('CMS_DIRECTORY_WWW', correctPath(WWWDirName(__FILE__)).'/admin');

    require_once(constant('CMS_DIRECTORY').'/includes/cache.inc');
    require_once(constant('CMS_DIRECTORY').'/includes/mikron.inc');
    require_once(constant('CMS_DIRECTORY').'/includes/acl.inc');

    $mikron = new MikronClass();
    $mikron_global_timer = new MikronTimer();

    define('SITE_NAME', $mikron->SiteManager->CurrentSite->sitename());
    define('CURRENTSITE_STYLE', constant('MIKRON_DIRECTORY').'/templates/'.constant('SITE_NAME').'/');
    define('CURRENTSITE_STYLE_WWW', constant('MIKRON_DIRECTORY_WWW').'/templates/'.constant('SITE_NAME').'/');
    define('CURRENTSITE_DIR', correctPath(constant('CMS_DIRECTORY').'/../sites/'.constant('SITE_NAME')));
    define('ENTITIES_CLASSES_FILE', constant('CURRENTSITE_DIR').'/private/entities.inc'); // файл сущностей

    // папка текущего сайта (в ней лежат все файлы относящиеся к конкретному сайту)
    if(!file_exists(constant('CURRENTSITE_DIR')) || !is_dir(constant('CURRENTSITE_DIR')))
    {
        CriticalError(sprintf('Директория сайта «%s» не существует.', constant('CURRENTSITE_DIR')));
    }

    // Main system files +10ms
    require_once(constant('CMS_DIRECTORY').'/includes/query.inc');
    require_once(constant('CMS_DIRECTORY').'/includes/baseobject.inc');
    require_once(constant('CMS_DIRECTORY').'/includes/dbaccess.inc'); // База данных
    require_once(constant('CMS_DIRECTORY').'/includes/instructions.inc');
    require_once(constant('CMS_DIRECTORY').'/includes/entity.inc'); // Entities/Сущности +8ms
    require_once(constant('CMS_DIRECTORY').'/includes/form.inc'); // Entities/Сущности +8ms
    if(file_exists(constant('ENTITIES_CLASSES_FILE')))
    {
        require_once(constant('ENTITIES_CLASSES_FILE'));
    }

    // File for export for current site/файл экспорта для текущего сайта
    $php_code_for_eval = null;
    $php_file_for_eval = null;
    $pos = stripos($_SERVER['SCRIPT_NAME'], constant('CMS_DIRECTORY_WWW'));
    define('ADMIN_CENTER', !($pos === false));

    $mikron->Initialize();

     // Add instructions/Добавление обработчика управляющей инструкции
    $mikron->OperatingInstructions->AddFunction('userform', 'OperatingInstruction_UserForm');
    $mikron->OperatingInstructions->AddFunction("ullist", 'ShowEntityAsList', $mikron->EntityManager);
    $mikron->OperatingInstructions->AddFunction("table", 'ShowEntityAsTable', $mikron->EntityManager);
    $mikron->OperatingInstructions->AddFunction('load', 'LoadEntity', $mikron->EntityManager);
    $mikron->OperatingInstructions->AddFunction('iconlink', 'OperatingInstruction_IconLink', $mikron->Graphics);
    // Добавление переменных
    $mikron->OperatingInstructions->AddVariable('HEADER', '{{$MikronCSS}}');
    $mikron->OperatingInstructions->AddVariable('FOOTER', '{{JSFiles}}');
    // $mikron->OperatingInstructions->AddVariable('REQUEST_URI', $_SERVER['REQUEST_URI']);
    $libdir = constant('MIKRON_LIBDIR');
    //$mikron->CSS->AddFile("$libdir/jquery/css/smoothness/jquery-ui-1.7.1.custom.css", 'Ingrid [http://www.reconstrukt.com/ingrid/#how]');        
    $mikron->JS->AddFile($libdir.'/jquery/jquery.js');
    //$mikron->JS->AddFile("$libdir/jquery/jquery.cookie.js");
    //$mikron->JS->AddFile("$libdir/jquery/jquery-ui-1.7.1.custom.min.js");
    //$mikron->JS->AddFile("$libdir/jquery/datepicker/localize/datepiker/ui.datepicker-ru.js");
    //$mikron->JS->AddFile("$libdir/jquery/jquery.validate.js");
        //$mikron->JS->AddFile("$libdir/jquery/jquery.form.js");
    // $mikron->JS->AddFile("$libdir/jquery/jquery.dropshadow.js", 'Drop shadow jQuery plugin');
    //$mikron->JS->AddFile("$libdir/jquery/jquery.hotkeys-0.7.9.min.js", 'Hotkeys jQuery plugin');
    require_once(constant('CURRENTSITE_DIR').'/private/site.inc');
    $mikron->InitUsers();
    $mikron->ACL->Refresh();

    // If not in admin-center/Если не в админке
    if(!constant('ADMIN_CENTER'))
    {
        $site_main_file = constant('CURRENTSITE_DIR').'/private/site_main.inc';
        require_once($site_main_file);
    }

    // Подключение модулей/плагинов системы. html_table и html_form должны грузиться первыми, т.к. от них зависят другие модули
    $mikron->Modules->Initialize();
    // Запуск приложений
    $mikron->Applications->RunApplications();

    function CriticalError($text, $error = null, $close_body = false)
    {
        $message = '';
        if($error != null && is_array($error) && isset($error['message']))
        {
            $message = '<br />'.$error['message'];
        }
        echo "<div class=\"mikroncms_error\">Critical error: <font color=\"red\">".$text."".$message."</font></div>";
        if($close_body)
        {
            global $mikron;
            if(isset($mikron))
            {
                $mikron->Page->EndBody();
            }
        }
        exit;
    }

    function Exception2($text, $code = 1024)
    {
        throw new Exception($text, (int)$code);
    }

    function CatchFunction($FunctionName, $parameters = null, & $object = null)
    {
        ob_start();
        if(is_object($object))
        {
            $object->$FunctionName($parameters);            
        }
        else
        {
            $FunctionName($parameters);
        }
        return ob_get_clean();
    }

    function correctPath($path)
    {
        return str_replace('\\', '/', $path);
    }

    function WWWDirName($file)
    {
        return str_replace($_SERVER['DOCUMENT_ROOT'], null, str_replace("\\", '/', dirname($file)));
    }
 
    function getdifftime($text, $return = false, $cleartime = false)
    {
        global $mikron_global_timer;
        $value = round($mikron_global_timer->elapsed(), 4);  
        if(!$cleartime)
        {
            $value = '<!-- '. round($value, 4). ' - '. $text. " -->\r\n";
        }
        if($return)
        {
            return $value;
        }
        echo $value;
    }

?>